<?php
/**
 * Created by PhpStorm.
 * User: peiyu
 * Date: 2019/7/3
 * Time: 14:46
 */

namespace app\common\model;

use think\Model;
use Db;
use Log;

class dictionary extends Model
{



    public static function get_($dic)
    {

        $catch_key = config("my.catchKEY.dictionary"). $dic ;
        $_v = cache($catch_key);
        if ($_v) return $_v;
        $config = self::where("key", $dic)->find();
        if (!$config) throw new \Exception("配置不能为空。表：dictionary，key：".$dic);
        $v = $config->value;
        if (!$v) throw new \Exception("配置不能为空。表：dictionary，key：".$config);
        $arr = json_decode($v, true);
        if ($arr) cache($catch_key, $arr, 3600);
        return $arr;

    }
/*
    private static function setDimension(array $arr)
    {
        $old = self::getDimension();
        $needadd = [];
        foreach ($arr as $key => $value) {
            if (!array_key_exists($key, $old)) {
                $needadd[] = $key;
            }
        }
        if ($needadd) {
            $needaddcolumns = config::checkDimension($needadd);
            if ($needaddcolumns) {

                $sql = "";
                try {
                    foreach ($needaddcolumns as $column) {
                        $sql = "ALTER TABLE `config` ADD COLUMN `" . $column . "`  varchar(50) NOT NULL DEFAULT '' COMMENT '" . $arr[$column] . "' ;";
                        Db::execute($sql);
                    }

                } catch (\Exception $e) {
                    $msg = "执行sql失败，请手动添加列后再次执行此次操作，详情查看日志。" . $e->getMessage() . ":sql：" . $sql;
                    Log::error($msg);
                    throw new \Exception($msg);
                }
            }

        }
        self::set_("dimension",$arr);

    }*/

    private static function set_($dic,array $arr){

        self::where("key", $dic)->update(["value" => json_encode($arr, JSON_UNESCAPED_UNICODE)]);
        $catch_key = config("my.catchKEY.dictionary"). $dic ;
        cache($catch_key, null);

    }


    public static function getTableData($dic)
    {
        $arr = self::get_($dic);
        $ret = [];
        foreach ($arr as $k => $v) {
            $ret[] = ["key" => $k, "title" => $v];
        }
        return $ret;
    }

    public static function saveTableData($dic,array $table)
    {

        $keys = [];
        $arr = [];
        foreach ($table as $item) {
            $k = trim($item["key"]);
            if (!$k) continue;
            if (in_array($k, $keys)) {
                throw new \Exception("key 不能重复");
            } else {
                $keys[] = $k;
            }
            $arr[$k] = trim($item["title"]);
        }
        //if($dic=="dimension")self::setDimension($arr);
        //else
        self::set_($dic,$arr);
    }


    /*//获得维度 常用
    public static function getDimension()
    {

        return self::get_("dimension");
    }*/
}